3 * Contain the EditPage class
8 * Splitting edit page/HTML interface from Article...
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
28 var $save = false, $preview = false, $diff = false;
29 var $minoredit = false, $watchthis = false, $recreate = false;
30 var $textbox1 = '', $textbox2 = '', $summary = '';
31 var $edittime = '', $section = '', $starttime = '';
32 var $oldid = 0, $editintro = '';
38 function EditPage( $article ) {
39 $this->mArticle
=& $article;
41 $this->mTitle
=& $wgTitle;
45 * This is the function that extracts metadata from the article body on the first view.
46 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
47 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
49 function extractMetaDataFromArticle () {
50 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
51 $this->mMetaData
= '' ;
52 if ( !$wgUseMetadataEdit ) return ;
53 if ( $wgMetadataWhitelist == '' ) return ;
55 $t = $this->mArticle
->getContent ( true ) ;
57 # MISSING : <nowiki> filtering
59 # Categories and language links
60 $t = explode ( "\n" , $t ) ;
61 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
62 $cat = $ll = array() ;
63 foreach ( $t AS $key => $x )
65 $y = trim ( strtolower ( $x ) ) ;
66 while ( substr ( $y , 0 , 2 ) == '[[' )
68 $y = explode ( ']]' , trim ( $x ) ) ;
69 $first = array_shift ( $y ) ;
70 $first = explode ( ':' , $first ) ;
71 $ns = array_shift ( $first ) ;
72 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
73 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
75 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
76 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
78 $x = implode ( ']]' , $y ) ;
80 $y = trim ( strtolower ( $x ) ) ;
84 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
85 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
86 $t = implode ( "\n" , $t ) ;
89 $sat = array () ; # stand-alone-templates; must be lowercase
90 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
91 $wl_article = new Article ( $wl_title ) ;
92 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
97 while ( substr ( $x , 0 , 1 ) == '*' )
100 $x = trim ( substr ( $x , 1 ) ) ;
104 $sat[] = strtolower ( $x ) ;
109 # Templates, but only some
110 $t = explode ( '{{' , $t ) ;
112 foreach ( $t AS $key => $x )
114 $y = explode ( '}}' , $x , 2 ) ;
115 if ( count ( $y ) == 2 )
118 $z = explode ( '|' , $z ) ;
119 $tn = array_shift ( $z ) ;
120 if ( in_array ( strtolower ( $tn ) , $sat ) )
122 $tl[] = '{{' . $y[0] . '}}' ;
124 $y = explode ( '}}' , $y[1] , 2 ) ;
126 else $t[$key] = '{{' . $x ;
128 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
131 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
132 $t = implode ( '' , $t ) ;
134 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
135 $this->mArticle
->mContent
= $t ;
136 $this->mMetaData
= $s ;
144 * This is the function that gets called for "action=edit". It
145 * sets up various member variables, then passes execution to
146 * another function, usually showEditForm()
148 * The edit form is self-submitting, so that when things like
149 * preview and edit conflicts occur, we get the same form back
150 * with the extra stuff added. Only when the final submission
151 * is made and all is well do we actually save and redirect to
152 * the newly-edited page.
155 global $wgOut, $wgUser, $wgRequest, $wgTitle;
157 $fname = 'EditPage::edit';
158 wfProfileIn( $fname );
159 wfDebug( "$fname: enter\n" );
161 // this is not an article
162 $wgOut->setArticleFlag(false);
164 $this->importFormData( $wgRequest );
165 $this->firsttime
= false;
168 $this->livePreview();
169 wfProfileOut( $fname );
173 if ( ! $this->mTitle
->userCanEdit() ) {
174 wfDebug( "$fname: user can't edit\n" );
175 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ), true );
176 wfProfileOut( $fname );
179 wfDebug( "$fname: Checking blocks\n" );
180 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
181 # When previewing, don't check blocked state - will get caught at save time.
182 # Also, check when starting edition is done against slave to improve performance.
183 wfDebug( "$fname: user is blocked\n" );
184 $this->blockedIPpage();
185 wfProfileOut( $fname );
188 if ( !$wgUser->isAllowed('edit') ) {
189 if ( $wgUser->isAnon() ) {
190 wfDebug( "$fname: user must log in\n" );
191 $this->userNotLoggedInPage();
192 wfProfileOut( $fname );
195 wfDebug( "$fname: read-only page\n" );
196 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ), true );
197 wfProfileOut( $fname );
201 if ( wfReadOnly() ) {
202 wfDebug( "$fname: read-only mode is engaged\n" );
203 if( $this->save ||
$this->preview
) {
204 $this->formtype
= 'preview';
205 } else if ( $this->diff
) {
206 $this->formtype
= 'diff';
208 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ) );
209 wfProfileOut( $fname );
214 $this->formtype
= 'save';
215 } else if ( $this->preview
) {
216 $this->formtype
= 'preview';
217 } else if ( $this->diff
) {
218 $this->formtype
= 'diff';
219 } else { # First time through
220 $this->firsttime
= true;
221 if( $this->previewOnOpen() ) {
222 $this->formtype
= 'preview';
224 $this->extractMetaDataFromArticle () ;
225 $this->formtype
= 'initial';
230 wfProfileIn( "$fname-business-end" );
232 $this->isConflict
= false;
233 // css / js subpages of user pages get a special treatment
234 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
236 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
237 * no matter it's current state
239 $this->deletedSinceEdit
= false;
240 if ( $this->edittime
!= '' ) {
241 /* Note that we rely on logging table, which hasn't been always there,
242 * but that doesn't matter, because this only applies to brand new
243 * deletes. This is done on every preview and save request. Move it further down
244 * to only perform it on saves
246 if ( $this->mTitle
->isDeleted() ) {
247 $this->lastDelete
= $this->getLastDelete();
248 if ( !is_null($this->lastDelete
) ) {
249 $deletetime = $this->lastDelete
->log_timestamp
;
250 if ( ($deletetime - $this->starttime
) > 0 ) {
251 $this->deletedSinceEdit
= true;
257 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
260 if( $this->mTitle
->isTalkPage() ) {
261 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
264 # Attempt submission here. This will check for edit conflicts,
265 # and redundantly check for locked database, blocked IPs, etc.
266 # that edit() already checked just in case someone tries to sneak
267 # in the back door with a hand-edited submission URL.
269 if ( 'save' == $this->formtype
) {
270 if ( !$this->attemptSave() ) {
271 wfProfileOut( "$fname-business-end" );
272 wfProfileOut( $fname );
277 # First time through: get contents, set time for conflict
279 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
280 $this->initialiseForm();
283 $this->showEditForm();
284 wfProfileOut( "$fname-business-end" );
285 wfProfileOut( $fname );
289 * Return true if this page should be previewed when the edit form
290 * is initially opened.
294 function previewOnOpen() {
296 return $wgUser->getOption( 'previewonfirst' ) ||
297 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
298 !$this->mTitle
->exists() );
304 function importFormData( &$request ) {
306 $fname = 'EditPage::importFormData';
307 wfProfileIn( $fname );
309 if( $request->wasPosted() ) {
310 # These fields need to be checked for encoding.
311 # Also remove trailing whitespace, but don't remove _initial_
312 # whitespace from the text boxes. This may be significant formatting.
313 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
314 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
315 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
316 # Truncate for whole multibyte characters. +5 bytes for ellipsis
317 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
319 $this->edittime
= $request->getVal( 'wpEdittime' );
320 $this->starttime
= $request->getVal( 'wpStarttime' );
321 if( is_null( $this->edittime
) ) {
322 # If the form is incomplete, force to preview.
323 wfDebug( "$fname: Form data appears to be incomplete\n" );
324 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
325 $this->preview
= true;
327 if( $this->tokenOk( $request ) ) {
328 # Some browsers will not report any submit button
329 # if the user hits enter in the comment box.
330 # The unmarked state will be assumed to be a save,
331 # if the form seems otherwise complete.
332 wfDebug( "$fname: Passed token check.\n" );
333 $this->preview
= $request->getCheck( 'wpPreview' );
334 $this->diff
= $request->getCheck( 'wpDiff' );
336 # Page might be a hack attempt posted from
337 # an external site. Preview instead of saving.
338 wfDebug( "$fname: Failed token check; forcing preview\n" );
339 $this->preview
= true;
342 $this->save
= ! ( $this->preview
OR $this->diff
);
343 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
344 $this->edittime
= null;
347 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
348 $this->starttime
= null;
351 $this->recreate
= $request->getCheck( 'wpRecreate' );
353 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
354 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
356 # Not a posted form? Start with nothing.
357 wfDebug( "$fname: Not a posted form.\n" );
358 $this->textbox1
= '';
359 $this->textbox2
= '';
360 $this->mMetaData
= '';
362 $this->edittime
= '';
363 $this->starttime
= wfTimestampNow();
364 $this->preview
= false;
367 $this->minoredit
= false;
368 $this->watchthis
= false;
369 $this->recreate
= false;
372 $this->oldid
= $request->getInt( 'oldid' );
374 # Section edit can come from either the form or a link
375 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
377 $this->live
= $request->getCheck( 'live' );
378 $this->editintro
= $request->getText( 'editintro' );
380 wfProfileOut( $fname );
384 * Make sure the form isn't faking a user's credentials.
386 * @param WebRequest $request
390 function tokenOk( &$request ) {
392 if( $wgUser->isAnon() ) {
393 # Anonymous users may not have a session
394 # open. Don't tokenize.
397 return $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
401 function showIntro() {
402 global $wgOut, $wgUser;
403 $addstandardintro=true;
404 if($this->editintro
) {
405 $introtitle=Title
::newFromText($this->editintro
);
406 if(isset($introtitle) && $introtitle->userCanRead()) {
407 $rev=Revision
::newFromTitle($introtitle);
409 $wgOut->addWikiText($rev->getText());
410 $addstandardintro=false;
414 if($addstandardintro) {
415 if ( $wgUser->isLoggedIn() )
416 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
418 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
424 * @return bool false if output is done, true if the rest of the form should be displayed
426 function attemptSave() {
427 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
429 $fname = 'EditPage::attemptSave';
430 wfProfileIn( $fname );
431 wfProfileIn( "$fname-checks" );
433 # Reintegrate metadata
434 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
435 $this->mMetaData
= '' ;
438 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
439 $this->spamPage ( $matches[0] );
440 wfProfileOut( "$fname-checks" );
441 wfProfileOut( $fname );
444 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
445 # Error messages or other handling should be performed by the filter function
446 wfProfileOut( $fname );
447 wfProfileOut( "$fname-checks" );
450 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1
, $this->section
) ) ) {
451 # Error messages or other handling should be performed by the filter function
452 wfProfileOut( $fname );
453 wfProfileOut( "$fname-checks" );
456 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
457 # Check block state against master, thus 'false'.
458 $this->blockedIPpage();
459 wfProfileOut( "$fname-checks" );
460 wfProfileOut( $fname );
464 if ( !$wgUser->isAllowed('edit') ) {
465 if ( $wgUser->isAnon() ) {
466 $this->userNotLoggedInPage();
467 wfProfileOut( "$fname-checks" );
468 wfProfileOut( $fname );
472 $wgOut->readOnlyPage();
473 wfProfileOut( "$fname-checks" );
474 wfProfileOut( $fname );
479 if ( wfReadOnly() ) {
480 $wgOut->readOnlyPage();
481 wfProfileOut( "$fname-checks" );
482 wfProfileOut( $fname );
485 if ( $wgUser->pingLimiter() ) {
486 $wgOut->rateLimited();
487 wfProfileOut( "$fname-checks" );
488 wfProfileOut( $fname );
492 # If the article has been deleted while editing, don't save it without
494 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
495 wfProfileOut( "$fname-checks" );
496 wfProfileOut( $fname );
500 wfProfileOut( "$fname-checks" );
502 # If article is new, insert it.
503 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
505 # Don't save a new article if it's blank.
506 if ( ( '' == $this->textbox1
) ) {
507 $wgOut->redirect( $this->mTitle
->getFullURL() );
508 wfProfileOut( $fname );
512 $isComment=($this->section
=='new');
513 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
514 $this->minoredit
, $this->watchthis
, false, $isComment);
516 wfProfileOut( $fname );
520 # Article exists. Check for edit conflict.
522 $this->mArticle
->clear(); # Force reload of dates, etc.
523 $this->mArticle
->forUpdate( true ); # Lock the article
525 if( ( $this->section
!= 'new' ) &&
526 ($this->mArticle
->getTimestamp() != $this->edittime
) )
528 $this->isConflict
= true;
530 $userid = $wgUser->getID();
532 if ( $this->isConflict
) {
533 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
534 $this->mArticle
->getTimestamp() . "'\n" );
535 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
538 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
539 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
542 # Suppress edit conflict with self, except for section edits where merging is required.
543 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
544 wfDebug( "Suppressing edit conflict, same user.\n" );
545 $this->isConflict
= false;
547 # switch from section editing to normal editing in edit conflict
548 if($this->isConflict
) {
550 if( $this->mergeChangesInto( $text ) ){
551 // Successful merge! Maybe we should tell the user the good news?
552 $this->isConflict
= false;
553 wfDebug( "Suppressing edit conflict, successful merge.\n" );
556 $this->textbox1
= $text;
557 wfDebug( "Keeping edit conflict, failed merge.\n" );
562 if ( $this->isConflict
) {
563 wfProfileOut( $fname );
568 wfProfileIn( "$fname-sectionanchor" );
570 if( $this->section
== 'new' ) {
571 if( $this->summary
!= '' ) {
572 $sectionanchor = $this->sectionAnchor( $this->summary
);
574 } elseif( $this->section
!= '' ) {
575 # Try to get a section anchor from the section source, redirect to edited section if header found
576 # XXX: might be better to integrate this into Article::replaceSection
577 # for duplicate heading checking and maybe parsing
578 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
579 # we can't deal with anchors, includes, html etc in the header for now,
580 # headline would need to be parsed to improve this
581 if($hasmatch and strlen($matches[2]) > 0) {
582 $sectionanchor = $this->sectionAnchor( $matches[2] );
585 wfProfileOut( "$fname-sectionanchor" );
587 // Save errors may fall down to the edit form, but we've now
588 // merged the section into full text. Clear the section field
589 // so that later submission of conflict forms won't try to
590 // replace that into a duplicated mess.
591 $this->textbox1
= $text;
594 # update the article here
595 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
596 $this->watchthis
, '', $sectionanchor ) ) {
597 wfProfileOut( $fname );
600 $this->isConflict
= true;
602 wfProfileOut( $fname );
607 * Initialise form fields in the object
608 * Called on the first invocation, e.g. when a user clicks an edit link
610 function initialiseForm() {
611 $this->edittime
= $this->mArticle
->getTimestamp();
612 $this->textbox1
= $this->mArticle
->getContent( true );
618 * Send the edit form and related headers to $wgOut
619 * @param $formCallback Optional callable that takes an OutputPage
620 * parameter; will be called during form output
621 * near the top, for captchas and the like.
623 function showEditForm( $formCallback=null ) {
624 global $wgOut, $wgUser, $wgAllowAnonymousMinor, $wgLang, $wgContLang;
626 $fname = 'EditPage::showEditForm';
627 wfProfileIn( $fname );
629 $sk =& $wgUser->getSkin();
631 $wgOut->setRobotpolicy( 'noindex,nofollow' );
633 # Enabled article-related sidebar, toplinks, etc.
634 $wgOut->setArticleRelated( true );
636 if ( $this->isConflict
) {
637 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
638 $wgOut->setPageTitle( $s );
639 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
641 $this->textbox2
= $this->textbox1
;
642 $this->textbox1
= $this->mArticle
->getContent( true );
643 $this->edittime
= $this->mArticle
->getTimestamp();
646 if( $this->section
!= '' ) {
647 if( $this->section
== 'new' ) {
648 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
650 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
651 if( !$this->preview
&& !$this->diff
) {
652 preg_match( "/^(=+)(.+)\\1/mi",
655 if( !empty( $matches[2] ) ) {
656 $this->summary
= "/* ". trim($matches[2])." */ ";
661 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
663 $wgOut->setPageTitle( $s );
664 if ( !$this->checkUnicodeCompliantBrowser() ) {
665 $this->mArticle
->setOldSubtitle();
666 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
668 if ( isset( $this->mArticle
)
669 && isset( $this->mArticle
->mRevision
)
670 && !$this->mArticle
->mRevision
->isCurrent() ) {
671 $this->mArticle
->setOldSubtitle();
672 $wgOut->addWikiText( wfMsg( 'editingold' ) );
677 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
678 } else if ( $this->isCssJsSubpage
and 'preview' != $this->formtype
) {
679 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
681 if( $this->mTitle
->isProtected('edit') ) {
682 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
685 $kblength = (int)(strlen( $this->textbox1
) / 1024);
686 if( $kblength > 29 ) {
687 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
690 $rows = $wgUser->getOption( 'rows' );
691 $cols = $wgUser->getOption( 'cols' );
693 $ew = $wgUser->getOption( 'editwidth' );
694 if ( $ew ) $ew = " style=\"width:100%\"";
697 $q = 'action=submit';
698 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
699 $action = $this->mTitle
->escapeLocalURL( $q );
701 $summary = wfMsg('summary');
702 $subject = wfMsg('subject');
703 $minor = wfMsg('minoredit');
704 $watchthis = wfMsg ('watchthis');
705 $save = wfMsg('savearticle');
706 $prev = wfMsg('showpreview');
707 $diff = wfMsg('showdiff');
709 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
711 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
712 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
713 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
714 htmlspecialchars( wfMsg( 'newwindow' ) );
716 global $wgRightsText;
717 $copywarn = "<div id=\"editpage-copywarn\">\n" .
718 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
719 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
720 $wgRightsText ) . "\n</div>";
722 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
723 # prepare toolbar for edit buttons
724 $toolbar = $this->getEditToolbar();
729 // activate checkboxes if user wants them to be always active
730 if( !$this->preview
&& !$this->diff
) {
731 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis
= true;
732 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
734 // activate checkbox also if user is already watching the page,
735 // require wpWatchthis to be unset so that second condition is not
736 // checked unnecessarily
737 if( !$this->watchthis
&& $this->mTitle
->userIsWatching() ) $this->watchthis
= true;
742 if ( $wgUser->isLoggedIn() ||
$wgAllowAnonymousMinor ) {
744 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
745 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
746 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
751 if ( $wgUser->isLoggedIn() ) {
752 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
753 ($this->watchthis?
" checked='checked'":"").
754 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
755 "<label for='wpWatchthis' title=\"" .
756 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
759 $checkboxhtml = $minoredithtml . $watchhtml;
761 $wgOut->addHTML( '<div id="wikiPreview">' );
762 if ( 'preview' == $this->formtype
) {
763 $previewOutput = $this->getPreviewText();
764 if ( $wgUser->getOption('previewontop' ) ) {
765 $wgOut->addHTML( $previewOutput );
766 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
767 $this->mArticle
->closeShowCategory();
769 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
772 $wgOut->addHTML( '</div>' );
773 if ( 'diff' == $this->formtype
) {
774 if ( $wgUser->getOption('previewontop' ) ) {
775 $wgOut->addHTML( $this->getDiff() );
780 # if this is a comment, show a subject line at the top, which is also the edit summary.
781 # Otherwise, show a summary field at the bottom
782 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
783 if( $this->section
== 'new' ) {
784 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
787 $commentsubject = '';
788 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
791 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
792 if( !$this->preview
&& !$this->diff
) {
793 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
795 $templates = $this->getTemplatesUsed();
797 global $wgLivePreview;
798 if ( $wgLivePreview ) {
799 $liveOnclick = $this->doLivePreviewScript();
804 global $wgUseMetadataEdit ;
805 if ( $wgUseMetadataEdit ) {
806 $metadata = $this->mMetaData
;
807 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
808 $helppage = Title
::newFromText( wfMsg( "metadata_page" ) ) ;
809 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
810 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
812 else $metadata = "" ;
816 if ($this->deletedSinceEdit
) {
817 if ( 'save' != $this->formtype
) {
818 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
820 // Hide the toolbar and edit area, use can click preview to get it back
821 // Add an confirmation checkbox and explanation.
823 $hidden = 'type="hidden" style="display:none;"';
824 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
826 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
827 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
831 $safemodehtml = $this->checkUnicodeCompliantBrowser()
833 : "<input type='hidden' name=\"safemode\" value='1' />\n";
835 $wgOut->addHTML( <<<END
837 <form id="editform" name="editform" method="post" action="$action"
838 enctype="multipart/form-data">
841 if( is_callable( $formCallback ) ) {
842 call_user_func_array( $formCallback, array( &$wgOut ) );
844 $wgOut->addHTML( <<<END
847 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
848 cols='{$cols}'{$ew} $hidden>
850 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
857 <div class='editButtons'>
858 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
859 " title=\"".wfMsg('tooltip-save')."\"/>
860 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
861 " title=\"".wfMsg('tooltip-preview')."\"/>
862 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
863 " title=\"".wfMsg('tooltip-diff')."\"/> <span class='editHelp'>{$cancel} | {$edithelp}</span></div>
865 <div class='templatesUsed'>
869 $wgOut->addWikiText( $copywarn );
871 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
872 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
873 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
875 if ( $wgUser->isLoggedIn() ) {
877 * To make it harder for someone to slip a user a page
878 * which submits an edit form to the wiki without their
879 * knowledge, a random token is associated with the login
880 * session. If it's not passed back with the submission,
881 * we won't save the page, or render user JavaScript and
884 $token = htmlspecialchars( $wgUser->editToken() );
885 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
889 if ( $this->isConflict
) {
890 require_once( "DifferenceEngine.php" );
891 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
892 DifferenceEngine
::showDiff( $this->textbox2
, $this->textbox1
,
893 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
895 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
896 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
897 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
899 $wgOut->addHTML( "</form>\n" );
900 if ( $this->formtype
== 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
901 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
903 if ( $this->formtype
== 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
904 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
905 $wgOut->addHTML( $this->getDiff() );
908 wfProfileOut( $fname );
912 * Prepare a list of templates used by this page. Returns HTML.
914 function getTemplatesUsed() {
917 $fname = 'EditPage::getTemplatesUsed';
918 wfProfileIn( $fname );
920 $sk =& $wgUser->getSkin();
923 $articleTemplates = $this->mArticle
->getUsedTemplates();
924 if ( count( $articleTemplates ) > 0 ) {
925 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
926 foreach ( $articleTemplates as $tpl ) {
927 if ( $titleObj = Title
::makeTitle( NS_TEMPLATE
, $tpl ) ) {
928 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
931 $templates .= '</ul>';
933 wfProfileOut( $fname );
938 * Live Preview lets us fetch rendered preview page content and
939 * add it to the page without refreshing the whole page.
940 * If not supported by the browser it will fall through to the normal form
943 * This function outputs a script tag to support live preview, and
944 * returns an onclick handler which should be added to the attributes
945 * of the preview button
947 function doLivePreviewScript() {
948 global $wgStylePath, $wgJsMimeType, $wgOut;
949 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
950 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
951 '"></script>' . "\n" );
952 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
953 return 'onclick="return !livePreview('.
954 'getElementById(\'wikiPreview\'),' .
955 'editform.wpTextbox1.value,' .
956 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
959 function getLastDelete() {
960 $dbr =& wfGetDB( DB_SLAVE
);
961 $fname = 'EditPage::getLastDelete';
963 array( 'logging', 'user' ),
973 array( 'log_namespace' => $this->mTitle
->getNamespace(),
974 'log_title' => $this->mTitle
->getDBkey(),
975 'log_type' => 'delete',
976 'log_action' => 'delete',
977 'user_id=log_user' ),
979 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
981 if($dbr->numRows($res) == 1) {
982 while ( $x = $dbr->fetchObject ( $res ) )
984 $dbr->freeResult ( $res ) ;
994 function getPreviewText() {
995 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
997 $fname = 'EditPage::getPreviewText';
998 wfProfileIn( $fname );
1000 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1001 "<div class='previewnote'>" . $wgOut->parse( wfMsg( 'previewnote' ) ) . "</div>\n";
1002 if ( $this->isConflict
) {
1003 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1006 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1007 $parserOptions->setEditSection( false );
1009 # don't parse user css/js, show message about preview
1010 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1012 if ( $this->isCssJsSubpage
) {
1013 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1014 $previewtext = wfMsg('usercsspreview');
1015 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1016 $previewtext = wfMsg('userjspreview');
1018 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1019 $wgOut->addHTML( $parserOutput->mText
);
1020 wfProfileOut( $fname );
1021 return $previewhead;
1023 # if user want to see preview when he edit an article
1024 if( $wgUser->getOption('previewonfirst') and ($this->textbox1
== '')) {
1025 $this->textbox1
= $this->mArticle
->getContent(true);
1028 $toparse = $this->textbox1
;
1030 # If we're adding a comment, we need to show the
1031 # summary as the headline
1032 if($this->section
=="new" && $this->summary
!="") {
1033 $toparse="== {$this->summary} ==\n\n".$toparse;
1036 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1038 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1039 $wgTitle, $parserOptions );
1041 $previewHTML = $parserOutput->mText
;
1043 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
1044 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
1046 wfProfileOut( $fname );
1047 return $previewhead . $previewHTML;
1054 function blockedIPpage() {
1055 global $wgOut, $wgUser, $wgContLang;
1057 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
1058 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1059 $wgOut->setArticleRelated( false );
1061 $id = $wgUser->blockedBy();
1062 $reason = $wgUser->blockedFor();
1065 if ( is_numeric( $id ) ) {
1066 $name = User
::whoIs( $id );
1070 $link = '[[' . $wgContLang->getNsText( NS_USER
) .
1071 ":{$name}|{$name}]]";
1073 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
1074 $wgOut->returnToMain( false );
1080 function userNotLoggedInPage() {
1083 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1084 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1085 $wgOut->setArticleRelated( false );
1087 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1088 $wgOut->returnToMain( false );
1094 function spamPage ( $match = false )
1097 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1098 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1099 $wgOut->setArticleRelated( false );
1101 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1103 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1105 $wgOut->returnToMain( false );
1112 function mergeChangesInto( &$editText ){
1113 $fname = 'EditPage::mergeChangesInto';
1114 wfProfileIn( $fname );
1116 $db =& wfGetDB( DB_MASTER
);
1118 // This is the revision the editor started from
1119 $baseRevision = Revision
::loadFromTimestamp(
1120 $db, $this->mArticle
->mTitle
, $this->edittime
);
1121 if( is_null( $baseRevision ) ) {
1122 wfProfileOut( $fname );
1125 $baseText = $baseRevision->getText();
1127 // The current state, we want to merge updates into it
1128 $currentRevision = Revision
::loadFromTitle(
1129 $db, $this->mArticle
->mTitle
);
1130 if( is_null( $currentRevision ) ) {
1131 wfProfileOut( $fname );
1134 $currentText = $currentRevision->getText();
1136 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1137 $editText = $result;
1138 wfProfileOut( $fname );
1141 wfProfileOut( $fname );
1147 * Check if the browser is on a blacklist of user-agents known to
1148 * mangle UTF-8 data on form submission. Returns true if Unicode
1149 * should make it through, false if it's known to be a problem.
1153 function checkUnicodeCompliantBrowser() {
1154 global $wgBrowserBlackList;
1155 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1156 // No User-Agent header sent? Trust it by default...
1159 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1160 foreach ( $wgBrowserBlackList as $browser ) {
1161 if ( preg_match($browser, $currentbrowser) ) {
1169 * Format an anchor fragment as it would appear for a given section name
1170 * @param string $text
1174 function sectionAnchor( $text ) {
1175 $headline = Sanitizer
::decodeCharReferences( $text );
1177 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1178 $headline = trim( $headline );
1179 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1180 $replacearray = array(
1185 array_keys( $replacearray ),
1186 array_values( $replacearray ),
1191 * Shows a bulletin board style toolbar for common editing functions.
1192 * It can be disabled in the user preferences.
1193 * The necessary JavaScript code can be found in style/wikibits.js.
1195 function getEditToolbar() {
1196 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1199 * toolarray an array of arrays which each include the filename of
1200 * the button image (without path), the opening tag, the closing tag,
1201 * and optionally a sample text that is inserted between the two when no
1202 * selection is highlighted.
1203 * The tip text is shown when the user moves the mouse over the button.
1205 * Already here are accesskeys (key), which are not used yet until someone
1206 * can figure out a way to make them work in IE. However, we should make
1207 * sure these keys are not defined on the edit page.
1210 array( 'image'=>'button_bold.png',
1212 'close' => "\'\'\'",
1213 'sample'=> wfMsg('bold_sample'),
1214 'tip' => wfMsg('bold_tip'),
1217 array( 'image'=>'button_italic.png',
1220 'sample'=> wfMsg('italic_sample'),
1221 'tip' => wfMsg('italic_tip'),
1224 array( 'image'=>'button_link.png',
1227 'sample'=> wfMsg('link_sample'),
1228 'tip' => wfMsg('link_tip'),
1231 array( 'image'=>'button_extlink.png',
1234 'sample'=> wfMsg('extlink_sample'),
1235 'tip' => wfMsg('extlink_tip'),
1238 array( 'image'=>'button_headline.png',
1240 'close' => " ==\\n",
1241 'sample'=> wfMsg('headline_sample'),
1242 'tip' => wfMsg('headline_tip'),
1245 array( 'image'=>'button_image.png',
1246 'open' => '[['.$wgLang->getNsText(NS_IMAGE
).":",
1248 'sample'=> wfMsg('image_sample'),
1249 'tip' => wfMsg('image_tip'),
1252 array( 'image' =>'button_media.png',
1253 'open' => '[['.$wgLang->getNsText(NS_MEDIA
).':',
1255 'sample'=> wfMsg('media_sample'),
1256 'tip' => wfMsg('media_tip'),
1259 array( 'image' =>'button_math.png',
1260 'open' => "\\<math\\>",
1261 'close' => "\\</math\\>",
1262 'sample'=> wfMsg('math_sample'),
1263 'tip' => wfMsg('math_tip'),
1266 array( 'image' =>'button_nowiki.png',
1267 'open' => "\\<nowiki\\>",
1268 'close' => "\\</nowiki\\>",
1269 'sample'=> wfMsg('nowiki_sample'),
1270 'tip' => wfMsg('nowiki_tip'),
1273 array( 'image' =>'button_sig.png',
1277 'tip' => wfMsg('sig_tip'),
1280 array( 'image' =>'button_hr.png',
1281 'open' => "\\n----\\n",
1284 'tip' => wfMsg('hr_tip'),
1288 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1290 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1291 foreach($toolarray as $tool) {
1293 $image=$wgStylePath.'/common/images/'.$tool['image'];
1294 $open=$tool['open'];
1295 $close=$tool['close'];
1296 $sample = wfEscapeJsString( $tool['sample'] );
1298 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1299 // Older browsers show a "speedtip" type message only for ALT.
1300 // Ideally these should be different, realistically they
1301 // probably don't need to be.
1302 $tip = wfEscapeJsString( $tool['tip'] );
1304 #$key = $tool["key"];
1306 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1309 $toolbar.="document.writeln(\"</div>\");\n";
1310 $toolbar.="/*]]>*/\n</script>";
1315 * Output preview text only. This can be sucked into the edit page
1316 * via JavaScript, and saves the server time rendering the skin as
1317 * well as theoretically being more robust on the client (doesn't
1318 * disturb the edit box's undo history, won't eat your text on
1321 * @todo This doesn't include category or interlanguage links.
1322 * Would need to enhance it a bit, maybe wrap them in XML
1323 * or something... that might also require more skin
1324 * initialization, so check whether that's a problem.
1326 function livePreview() {
1329 header( 'Content-type: text/xml' );
1330 header( 'Cache-control: no-cache' );
1332 echo $this->getPreviewText( false, false );
1337 * Get a diff between the current contents of the edit box and the
1338 * version of the page we're editing from.
1340 * If this is a section edit, we'll replace the section as for final
1341 * save and then make a comparison.
1343 * @return string HTML
1345 function getDiff() {
1348 require_once( 'DifferenceEngine.php' );
1349 $oldtext = $this->mArticle
->fetchContent();
1350 $newtext = $this->mArticle
->replaceSection(
1351 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1352 $oldtitle = wfMsg( 'currentrev' );
1353 $newtitle = wfMsg( 'yourtext' );
1354 if ( $oldtext != wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) ||
$newtext != '' ) {
1355 $difftext = DifferenceEngine
::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1358 return '<div id="wikiDiff">' . $difftext . '</div>';
1362 * Filter an input field through a Unicode de-armoring process if it
1363 * came from an old browser with known broken Unicode editing issues.
1365 * @param WebRequest $request
1366 * @param string $field
1370 function safeUnicodeInput( $request, $field ) {
1371 $text = rtrim( $request->getText( $field ) );
1372 return $request->getBool( 'safemode' )
1373 ?
$this->unmakesafe( $text )
1378 * Filter an output field through a Unicode armoring process if it is
1379 * going to an old browser with known broken Unicode editing issues.
1381 * @param string $text
1385 function safeUnicodeOutput( $text ) {
1387 $codedText = $wgContLang->recodeForEdit( $text );
1388 return $this->checkUnicodeCompliantBrowser()
1390 : $this->makesafe( $codedText );
1394 * A number of web browsers are known to corrupt non-ASCII characters
1395 * in a UTF-8 text editing environment. To protect against this,
1396 * detected browsers will be served an armored version of the text,
1397 * with non-ASCII chars converted to numeric HTML character references.
1399 * Preexisting such character references will have a 0 added to them
1400 * to ensure that round-trips do not alter the original data.
1402 * @param string $invalue
1406 function makesafe( $invalue ) {
1407 // Armor existing references for reversability.
1408 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1413 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1414 $bytevalue = ord( $invalue{$i} );
1415 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1416 $result .= chr( $bytevalue );
1418 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1419 $working = $working << 6;
1420 $working +
= ($bytevalue & 0x3F);
1422 if( $bytesleft <= 0 ) {
1423 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1425 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1426 $working = $bytevalue & 0x1F;
1428 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1429 $working = $bytevalue & 0x0F;
1431 } else { //1111 0xxx
1432 $working = $bytevalue & 0x07;
1440 * Reverse the previously applied transliteration of non-ASCII characters
1441 * back to UTF-8. Used to protect data from corruption by broken web browsers
1442 * as listed in $wgBrowserBlackList.
1444 * @param string $invalue
1448 function unmakesafe( $invalue ) {
1450 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1451 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1455 $hexstring .= $invalue{$i};
1457 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1459 // Do some sanity checks. These aren't needed for reversability,
1460 // but should help keep the breakage down if the editor
1461 // breaks one of the entities whilst editing.
1462 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1463 $codepoint = hexdec($hexstring);
1464 $result .= codepointToUtf8( $codepoint );
1466 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1469 $result .= substr( $invalue, $i, 1 );
1472 // reverse the transform that we made for reversability reasons.
1473 return strtr( $result, array( "�" => "&#x" ) );